using System;
using System.Collections.Generic;
using System.Text;
using Entity;
using ECommerce.Library.DataStructure;
using System.IO;
using System.Web;
using ECommerce.Library;

namespace AutoGear.BLL
{
    public class Coupon
    {
        private const string _couponImageRootPath = "~/upload/images/coupon/";
        private const int _largeThumbImageWidth = 100;
        private const int _smallThumbImageWidth = 45;


        private int _couponId;
        private string _couponName = String.Empty;
        private string _couponDescription = String.Empty;
        private double _couponAmount;
        private double _minimumAmount;
        private CouponCalculationIn _calculationIn;
        private CouponType _couponType;
        private string _couponImageUrl = String.Empty;
        private DateTime _createDate;
        private DateTime _expireDate;
        private bool _isActive;
        private bool _isDeleted;
        private int _partnerId;

        public int CouponId
        {
            get { return _couponId; }
        }

        public string CouponName
        {
            get { return _couponName; }
            set { _couponName = value; }
        }

        public string CouponDescription
        {
            get { return _couponDescription; }
            set { _couponDescription = value; }
        }

        public double CouponAmount
        {
            get { return _couponAmount; }
            set { _couponAmount = value; }
        }
        public double MinimumAmount
        {
            get { return _minimumAmount; }
            set { _minimumAmount = value; }
        }

        public CouponCalculationIn CalculationIn
        {
            get { return _calculationIn; }
            set { _calculationIn = value; }
        }

        public CouponType CouponType
        {
            get { return _couponType; }
            set { _couponType = value; }
        }

        public string CouponImageUrl
        {
            get { return _couponImageUrl; }
            set { _couponImageUrl = value; }
        }
        public DateTime CreateDate
        {
            get { return _createDate; }
        }
        public DateTime ExpireDate
        {
            get { return _expireDate; }
            set { _expireDate = value; }
        }

        public bool IsActive
        {
            get { return _isActive; }
            set { _isActive = value; }
        }
        public bool IsDeleted
        {
            get { return _isDeleted; }
            set { _isDeleted = value; }
        }

        public string CouponImageSmallThumbnail
        {
            get { return _couponImageUrl.Replace("_largethumb", "_smallthumb"); }
        }

        public string CouponImageLargeThumbnail
        {
            get { return _couponImageUrl; }
        }

        public string CouponImageMaxSize
        {
            get { return _couponImageUrl.Replace("_largethumb", "_max"); }
        }

        public int PartnerId
        {
            get { return _partnerId; }
            set { _partnerId = value; }
        }

        public Coupon()
        {

        }


        public Coupon(TblCoupon tblCoupon)
        {
            _couponId = tblCoupon.CouponId;
            _couponName = tblCoupon.CouponName;
            _couponDescription = tblCoupon.CouponDescription;
            _couponAmount = Convert.ToDouble(tblCoupon.CouponAmount);
            _minimumAmount = Convert.ToDouble(tblCoupon.MinAmount);
            _calculationIn = tblCoupon.CalculationIn == CouponCalculationIn.Dollar.ToString() ? CouponCalculationIn.Dollar : CouponCalculationIn.Percentage;
            _couponType = tblCoupon.CouponType == CouponType.Text.ToString() ? CouponType.Text : CouponType.Image;
            _couponImageUrl = tblCoupon.CouponImageUrl;
            _createDate = tblCoupon.CreateDate;
            _expireDate = tblCoupon.ExpireDate;
            _isActive = tblCoupon.IsActive;
            _isDeleted = tblCoupon.IsDeleted;
            _partnerId = tblCoupon.ProductBrandId;

        }

        public void Create()
        {
            if (!string.IsNullOrEmpty(_couponImageUrl))
            {
                string temporaryImagePath = _couponImageUrl;
                _couponImageUrl = UploadCouponLogo(temporaryImagePath, _couponName);
            }
            TblCoupon tblCoupon = new TblCoupon();
            tblCoupon.CouponName = _couponName;
            tblCoupon.CouponDescription = _couponDescription;
            tblCoupon.CouponAmount = Convert.ToDecimal(_couponAmount);
            tblCoupon.MinAmount = Convert.ToDecimal(_minimumAmount);
            tblCoupon.CalculationIn = _calculationIn.ToString();
            tblCoupon.CouponType = _couponType.ToString();
            tblCoupon.CouponImageUrl = _couponImageUrl;
            tblCoupon.CreateDate = DateTime.Now;
            tblCoupon.ExpireDate = _expireDate;
            tblCoupon.IsActive = _isActive;
            tblCoupon.IsDeleted = _isDeleted;
            tblCoupon.ProductBrandId = PartnerId;
            tblCoupon.Save();
        }

        public void Update()
        {
            if (!string.IsNullOrEmpty(_couponImageUrl))
            {
                string temporaryImagePath = _couponImageUrl;
                _couponImageUrl = UploadCouponLogo(temporaryImagePath, _couponName);
            }

            TblCoupon tblCoupon = TblCoupon.GetTblCouponByCouponId(_couponId);
            tblCoupon.CouponName = _couponName;
            tblCoupon.CouponDescription = _couponDescription;
            tblCoupon.CouponAmount = Convert.ToDecimal(_couponAmount);
            tblCoupon.MinAmount = Convert.ToDecimal(_minimumAmount);
            tblCoupon.CalculationIn = _calculationIn.ToString();
            tblCoupon.CouponType = _couponType.ToString();
            tblCoupon.CouponImageUrl = _couponImageUrl;
            tblCoupon.ExpireDate = _expireDate;
            tblCoupon.IsActive = _isActive;
            tblCoupon.IsDeleted = _isDeleted;
            tblCoupon.ProductBrandId = PartnerId;
            tblCoupon.Save();
        }

        public void Delete()
        {
            TblCoupon tblCoupon = TblCoupon.GetTblCouponByCouponId(_couponId);
            tblCoupon.IsDeleted = true;
            tblCoupon.Save();

            FileAccessUtility.DeleteFile(tblCoupon.CouponImageUrl);
            FileAccessUtility.DeleteFile(tblCoupon.CouponImageUrl.Replace("_largethumb", "_max"));
            FileAccessUtility.DeleteFile(tblCoupon.CouponImageUrl.Replace("_largethumb", "_smallthumb"));

        }

        public static void DeleteCoupon(List<int> ids)
        {
            TblCoupon.DeleteTblCouponList(ids);
        }

        public static void DeleteCoupon(ReadWriteCustomCollection<Coupon> Coupon)
        {
            foreach (Coupon coupon in Coupon)
            {
                coupon.Delete();
            }
        }

        public static Coupon Load(int couponId)
        {
            try
            {
                TblCoupon tmpTblCoupon = TblCoupon.GetTblCouponByCouponId(couponId);
                Coupon coupon = new Coupon(tmpTblCoupon);
                return coupon;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public static Coupon Load(string couponName)
        {
            try
            {
                ReadWriteCustomCollection<Coupon> coupons = GetActiveCouponList("CouponName");
                if (coupons != null && coupons.Count > 0)
                {
                    foreach (Coupon coupon in coupons)
                    {
                        if (coupon.CouponName.ToLower().Equals(couponName.ToLower()))
                        {
                            return coupon;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return null;
        }


        public static ReadWriteCustomCollection<Coupon> GetActiveCouponList(string orderBy)
        {
            return LoadFromCustomCollection(TblCouponExtended.GetActiveCouponPaged(orderBy, 0, 99999));
        }


        public static ReadWriteCustomCollection<Coupon> GetBackendCouponList(bool includeDeleted, string orderBy, int startIndex, int pageSize)
        {
            if (includeDeleted)
            {
                return LoadFromCustomCollection(TblCoupon.GetAllTblCouponPaged(orderBy, startIndex, pageSize));
            }
            else
            {
                return LoadFromCustomCollection(TblCouponExtended.GetNonDeletedCouponPaged(orderBy, startIndex, pageSize));
            }
        }

        public static int GetBackendCouponListCount(bool includeDeleted)
        {
            if (includeDeleted)
            {
                return TblCoupon.GetAllTblCouponPagedCount("", 0, 0);
            }
            else
            {
                return TblCouponExtended.GetNonDeletedCouponCount();
            }
        }

        public static ReadWriteCustomCollection<Coupon> GetBackendCouponListByCouponName(string CouponName, bool includeDeleted, string orderBy, int startIndex, int pageSize)
        {
            if (includeDeleted)
            {
                return LoadFromCustomCollection(TblCouponExtended.GetAllCouponByCouponNamePaged(CouponName, orderBy, startIndex, pageSize));
            }
            else
            {
                return LoadFromCustomCollection(TblCouponExtended.GetNonDeletedCouponByCouponNamePaged(CouponName, orderBy, startIndex, pageSize));
            }
        }

        public static int GetBackendCouponListByCouponNameCount(string CouponName, bool includeDeleted)
        {
            if (includeDeleted)
            {
                return TblCouponExtended.GetAllCouponByCouponNameCount(CouponName);
            }
            else
            {
                return TblCouponExtended.GetNonDeletedCouponByCouponNameCount(CouponName);
            }
        }


        public static ReadWriteCustomCollection<string> GetCouponTypes()
        {
            ReadWriteCustomCollection<string> couponType = new ReadWriteCustomCollection<string>();
            couponType.Add(CouponType.Text.ToString());
            couponType.Add(CouponType.Image.ToString());
            return couponType;
        }
        public static ReadWriteCustomCollection<string> GetCalculationIn()
        {
            ReadWriteCustomCollection<string> couponCalculationIn = new ReadWriteCustomCollection<string>();
            couponCalculationIn.Add(CouponCalculationIn.Dollar.ToString() + " ($)");
            couponCalculationIn.Add(CouponCalculationIn.Percentage.ToString() + " (%)");
            return couponCalculationIn;
        }




        private static ReadWriteCustomCollection<Coupon> LoadFromCustomCollection(ECommerce.DAL.CustomCollection<TblCoupon> tblCoupon)
        {
            ReadWriteCustomCollection<Coupon> result = new ReadWriteCustomCollection<Coupon>();
            for (int i = 0; i < tblCoupon.Count; i++)
            {
                result.Add(new Coupon(tblCoupon[i]));
            }
            return result;
        }


        public static string UploadCouponLogo(string temporaryImagePath, string logoFileName)
        {
            try
            {

                FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(temporaryImagePath));

                if (logoInfo.Exists)
                {
                    logoFileName = SiteUtility.CleanCategoryName(logoFileName.ToLower()) + logoInfo.Extension;
                    logoFileName = RandomizeImageFileName(logoFileName);

                    string outputFilePath = _couponImageRootPath + logoFileName;
                    System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(temporaryImagePath);
                    string largeThumbImagePath = null;
                    ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_max");
                    if (originalImageDimension.Width > _largeThumbImageWidth)
                    {
                        largeThumbImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, _largeThumbImageWidth, true, "_largethumb");
                    }
                    else
                    {
                        largeThumbImagePath = ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_largethumb");
                    }
                    if (originalImageDimension.Width > _smallThumbImageWidth)
                    {
                        ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, _smallThumbImageWidth, true, "_smallthumb");
                    }
                    else
                    {
                        ImageResizer.CreateThumbnail(temporaryImagePath, outputFilePath, originalImageDimension.Width, true, "_smallthumb");
                    }
                    FileAccessUtility.DeleteFile(temporaryImagePath);
                    return largeThumbImagePath;
                }
                else
                {
                    throw new Exception();
                }
            }


            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static string RandomizeImageFileName(string plainName)
        {
            if (string.IsNullOrEmpty(plainName))
                throw new ArgumentNullException("plainName in Coupon.RandomizeImageFileName()");

            int indexOfDot = plainName.LastIndexOf('.');
            string extension = plainName.Substring(indexOfDot);

            if (plainName.Contains("_"))
            {
                int indexOfGuid = plainName.LastIndexOf('_');

                if (indexOfGuid > 0 && indexOfGuid < plainName.Length)
                {
                    string actualName = plainName.Substring(0, indexOfGuid + 1);
                    return actualName + Guid.NewGuid().ToString().Replace("-", "") + extension;
                }
            }
            else
            {
                if (indexOfDot > 0 && indexOfDot < plainName.Length)
                {
                    string actualName = plainName.Substring(0, indexOfDot + 1);
                    return actualName + Guid.NewGuid().ToString().Replace("-", "") + extension;
                }
            }

            return null;
        }

    }
}
